import { Hono } from "hono";
import { z } from "zod";
import validator from "../middlewares/validate";
import { MoodService } from "../services/mood";
import Responder from "../middlewares/response";
import { authMiddleware } from "../middlewares/auth";

const mood = new Hono();
const moodService = new MoodService();

mood.use("*", authMiddleware);

// 验证 schema
const createMoodSchema = z.object({
  mood: z.object({
    level: z.number().min(1).max(5)
  }),
  remark: z.string()
});

const updateMoodSchema = z.object({
  mood: z.object({
    level: z.number().min(1).max(5)
  }).optional(),
  remark: z.string().optional()
});

// 获取所有心情记录
mood.get("/", async (c) => {
  const userId = c.get("userId");
  const moods = await moodService.getMoods(userId);
  return Responder.success().setData(moods).build(c);
});

// 创建心情记录
mood.post("/", validator("json", createMoodSchema), async (c) => {
  const userId = c.get("userId");
  const data = c.req.valid("json");
  
  const mood = await moodService.createMood({
    userId,
    ...data
  });

  return Responder.success("心情记录创建成功").setData(mood).build(c);
});

// 获取单个心情记录
mood.get("/:id", async (c) => {
  const userId = c.get("userId");
  const moodId = c.req.param("id");
  
  const mood = await moodService.getMood(userId, moodId);
  return Responder.success().setData(mood).build(c);
});

// 更新心情记录
mood.put("/:id", validator("json", updateMoodSchema), async (c) => {
  const userId = c.get("userId");
  const moodId = c.req.param("id");
  const data = c.req.valid("json");

  const mood = await moodService.updateMood(userId, moodId, data);
  return Responder.success("心情记录更新成功").setData(mood).build(c);
});

// 删除心情记录
mood.delete("/:id", async (c) => {
  const userId = c.get("userId");
  const moodId = c.req.param("id");

  await moodService.deleteMood(userId, moodId);
  return Responder.success("心情记录删除成功").build(c);
});

// 获取心情统计数据
mood.get("/stats", async (c) => {
  const userId = c.get("userId");
  const stats = await moodService.getMoodStats(userId);
  return Responder.success().setData(stats).build(c);
});

export default mood;
